#include "result.h"
#include "constants.h"
#include "tools.h"
#include <QTextDocument>
#include <QMessageBox>
#include <QDebug>
#include <QPrintDialog>
#include <QPrinter>
#include <QFile>
#include <QTextStream>
#include <QDir>

using namespace Constants;
using namespace ToolsSpace;

Result::Result(QObject * parent)
{
    setupUi(this);
    setWindowModality(Qt::NonModal);
    numberOfResultsLabel->setText("");
    m_model = new QStandardItemModel(0,FieldsModelResults_MaxParam,this);
    tableView->setModel(m_model);
    tableView->setSortingEnabled(true);
    tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    patienteleButton->setChecked(true);
    separateurEdit->setText(",");
    Tools tool(this);
    m_pathToPersoDatas = tool.pathToPersonalDatas();
    QStringList files;
    files = filesOffList();
    filesOffComboBox->addItems(files);
    connect(deleteButton,SIGNAL(pressed()),this,SLOT(deleteLineOfResultsModel()));
    connect(printButton,SIGNAL(pressed()),this,SLOT(printTable()));
}

Result::~Result(){}

void Result::setResults(QHash<QString,QString> hashResults)
{
    enum NameFirstname
    {
        HASH_NAME=0,
        HASH_FIRSTNAME
        };
    QString separateur = separateurEdit->text().trimmed();
    QString fichieroff = filesOffComboBox->currentText();
    QStringList listOffNames;
    QStringList listOffFirstnames;    
    QStringList listOffIds;
    QFile file(m_pathToPersoDatas+"/"+fichieroff);
    if (!file.open(QIODevice::ReadOnly))
    {
    	qWarning() << __FILE__ << QString::number(__LINE__) << "unable to open : " << m_pathToPersoDatas+"/"+fichieroff;
        }
    QTextStream stream(&file);
    while (!stream.atEnd())
    {
    	QString line = stream.readLine();
    	QStringList l;
    	l = line.split(",",QString::SkipEmptyParts);
    	listOffNames << l[NAME_PATIENTELE_AMELI];
    	listOffFirstnames << l[FIRSTNAME_PATIENTELE_AMELI];
    	listOffIds << l[DATE_NAISS_PATIENTELE_AMELI];
        }
    QString results;
    for (int i = 0; i < hashResults.count(); ++i)
    {
          QString id = hashResults.keys()[i];
          QString nameFirstname = hashResults.values()[i];
          QStringList namelist = nameFirstname.split(";");
          QString name;
          QString firstname;
          if (namelist.size()>1)
          {
                name = namelist[HASH_NAME];
                firstname = namelist[HASH_FIRSTNAME];
              }
          if (i==0)
          {
                qDebug() << __FILE__ << QString::number(__LINE__) << " id name firstname =" << id << name << firstname ;
              }
           bool condition = true;
           if (fichiersoffButton->isChecked())
           {
           	condition = listOffNames.contains(name)&& listOffFirstnames.contains(firstname)&& listOffIds.contains(id);
               }
           if (patienteleButton->isChecked())
           {
           	condition = !(listOffNames.contains(name)&& listOffFirstnames.contains(firstname));
               }
           if (condition)
           {
           	   	continue;
               }
           QStandardItem * itId = new QStandardItem(id);
           QStandardItem * itName = new QStandardItem(name);
           QStandardItem * itFirstName = new QStandardItem(firstname);
           QList<QStandardItem*> list;
           list << itId << itName << itFirstName ;
           m_model->appendRow(list);
           m_listOfReturnedId << id;
        }
        qDebug() << __FILE__ << QString::number(__LINE__) << " m_listOfReturnedId =" << QString::number(m_listOfReturnedId.size()) ;
        
    QString numberOfResults = trUtf8("Nombre de dossiers = ")+QString::number(m_listOfReturnedId.count());
    numberOfResultsLabel->setText(numberOfResults);
}

void Result::deleteLineOfResultsModel()
{
    QString fichieroff = filesOffComboBox->currentText();
    QItemSelectionModel *selectionmodel = new QItemSelectionModel(m_model);
    selectionmodel = tableView->selectionModel();
    QFile file(m_pathToPersoDatas+"/"+fichieroff);
    if (!file.open(QIODevice::ReadWrite|QIODevice::Append))
    {
    	qWarning() << __FILE__ << QString::number(__LINE__) << "unable to open fileoff" ;
        }
    QTextStream stream(&file);
    QStringList listtoremove;
    QModelIndexList listofselectedrows = selectionmodel->selectedRows(0);
    QString essai;
    for (int r = 0; r < listofselectedrows.size(); ++r )
    {
        int row = listofselectedrows.at(r).row();
        essai += QString::number(row);
        listtoremove << m_model->data(m_model->index(row,ID_RESULTS),Qt::DisplayRole).toString();
    	}
    qDebug() << __FILE__ << QString::number(__LINE__) << essai ;
    for (int i = 0; i < listtoremove.size(); ++i )
    {
    	QString guid = listtoremove[i];
    	for (int r = 0; r < m_model->rowCount(); ++r )
    	{
    		QString id = m_model->data(m_model->index(r,ID_RESULTS),Qt::DisplayRole).toString();
    		if (guid == id)
    		{
    		    m_model->removeRows(r,1);
    		    }
    		}
    	}
    if (!m_model->submit())
    {
          QMessageBox::warning(0,trUtf8("Warning"),trUtf8("Unable to delete row."),QMessageBox::Ok);
        }
    QString numberOfResults = trUtf8("Nombre de dossiers = ")+QString::number(m_model->rowCount());
    numberOfResultsLabel->setText(numberOfResults);
}

QStringList Result::getListOfId()
{
    return m_listOfReturnedId;
}

void Result::printTable()
{
    QString htmlDocument = "<html><body><font size=3>";
    htmlDocument += "<TABLE BORDER=1>";
    htmlDocument += "<CAPTION><font color = red size = 6>"+trUtf8("Liste des patients concernés")+"</font></CAPTION>";
    htmlDocument += "<TR>";
    htmlDocument += "<TH><font color = blue><bold>"+tr("Nom")+"</bold></font></TH>";
    htmlDocument += "<TH><font color = blue><bold>"+tr("Prénom")+"</bold></font></TH>";
    htmlDocument += "<TH><font color = blue><bold>"+tr("ID")+"</bold></font></TH>";
    htmlDocument += "</TR>";
    for (int row = 0; row < m_model->rowCount(); ++row)
    {
          htmlDocument += "<TR>";
          for (int col = 0; col < FieldsModelResults_MaxParam; ++col)
          {
              htmlDocument += "<TD>";
              htmlDocument += m_model->data(m_model->index(row,col),Qt::DisplayRole).toString();
              htmlDocument += "</TD>";
              }
           htmlDocument += "</TR>";
        }
    htmlDocument += "</TABLE>";
    htmlDocument += "<BR/>";
    htmlDocument += tr("nombre = ")+QString::number(m_model->rowCount());
    htmlDocument += "</font></body></html>";
    QTextDocument *doc = new QTextDocument(this);
    doc->setHtml(htmlDocument);
    QPrinter *printer = new QPrinter;
    QPrintDialog *printdialog = new QPrintDialog(printer,this);
    printdialog               ->setWindowTitle(tr("Imprimer"));
    printdialog               ->exec();
    doc->print(printer);
}

QStringList Result::filesOffList()
{
    Tools t;
    QString pathtodatas = t.pathToPersonalDatas();    
    qDebug() << __FILE__ << QString::number(__LINE__) << "pathToPersonalDatas = " << pathtodatas;
    QDir datasdir(pathtodatas);
    QStringList listoffiles;
    listoffiles = datasdir.entryList();
    listoffiles.removeAll(".");
    listoffiles.removeAll("..");
    qDebug() << __FILE__ << QString::number(__LINE__) << "files = " << listoffiles.join(",");
    return listoffiles;
}
